package com.hdu.other.dp.treeDP;

import java.util.HashMap;
import java.util.Map;

public class lc437 {


    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    class Solution {
        int ans;
        Map<Long, Integer> presum2count = new HashMap<>();

        public int pathSum(TreeNode root, int targetSum) {
            presum2count.put(0l, 1);
            f(root, targetSum, 0);
            return ans;
        }

        void f(TreeNode root, int targetSum, long curSum) {
            if (root == null) {
                return;
            }
            ans += presum2count.getOrDefault(curSum + root.val - targetSum, 0);
            presum2count.put(curSum + root.val, presum2count.getOrDefault(curSum + root.val, 0) + 1);
            f(root.left, targetSum, curSum + root.val);
            f(root.right, targetSum, curSum + root.val);
            presum2count.put(curSum + root.val, presum2count.getOrDefault(curSum + root.val, 0) - 1);
        }
    }
}
